let userinfo = null
let api = require('./api.js')
export default {
	async userInfo() {
		try {
			let data = await api.getUserInfo()
			let body = data.data
			if (body.code == 200) {
				userinfo = body.data
				return userinfo
			}
			// uni.showToast({
			// 	title: '登录信息过期，请重新登录',
			// 	duration: 2000,
			// 	icon: 'none'
			// });
			// uni.removeStorageSync('userToken');
		} catch (e) {
			return null
		}
		return null
	},
	async loginOut() {
		if (userinfo?.token) {
			await api.loginOut()
			uni.removeStorageSync('userToken');
			userinfo = null
			uni.showToast({
				title: '退出登录成功',
				duration: 2000,
				icon: 'none'
			});
		} else {
			uni.showToast({
				title: '请先登录',
				duration: 2000,
				icon: 'error'
			});
		}
		return userinfo
	},
	async watchHistry(vid) {
		if (!userinfo?.token) await this.userInfo();
		let h = []
		if (userinfo?.token) {
			try {
				h = (await api.getVideoHistry({
					vid: vid || ''
				})).data.data
			} catch (e) {}
		} else {
			try {
				h = uni.getStorageSync('watchHistry');
				if (vid) {
					for (let v of h) {
						if (v.vod_id == vid) return [v]
					}
				} else
					h.sort((a, b) => {
						return b.watchTime - a.watchTime
					})
			} catch (e) {}
		}
		uni.setStorageSync('watchHistry', h);
		return h
	},
	async upWatchHistry(e) {
		if (userinfo?.token) {
			try {
				e.userToken = userinfo.token
				h = api.upVideoHistry(e)
			} catch (e) {}
		} else {
			try {
				const histry = uni.getStorageSync('watchHistry') || [];
				let find = -1
				for (let i in histry) {
					let v = histry[i]
					if (v.vod_id == e.vod_id) {
						histry[i] = e
						find = i
						break
					}
				}
				if (find == -1) histry.push(e)
				uni.setStorageSync('watchHistry', histry);
			} catch (e) {}
		}
	}
}